package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.MemberStoredValueCardDTO;
import com.ruoyi.system.dto.TransferAccountsDTO;
import com.ruoyi.system.dto.TransferDTO;
import com.ruoyi.system.mapper.MemberStoredValueCardMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BookingNumberGenerator;
import com.ruoyi.system.util.StoreIdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 会员储值卡信息Service业务层实现
 */
@Service
public class MemberStoredValueCardServiceImpl extends ServiceImpl<MemberStoredValueCardMapper, MemberStoredValueCard>
        implements IMemberStoredValueCardService {

    @Autowired
    private IMemberListService memberListService;
    @Autowired
    private StoreIdUtils storeIdUtils;

    @Autowired
    private IStoredValueCardManagementService storedValueCardManagementService;

    @Autowired
    private MemberRechargeRecordsService rechargeRecordsService;

    @Autowired
    private IMemberChangeRecordsService changeRecordsService;


    @Override
    public IPage<MemberStoredValueCard> byPage(MemberStoredValueCard memberStoredValueCard) {
        LambdaQueryWrapper<MemberStoredValueCard> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getMemberId()), MemberStoredValueCard::getMemberId, memberStoredValueCard.getMemberId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getCardNumber()), MemberStoredValueCard::getCardNumber, memberStoredValueCard.getCardNumber());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getMemberPhone()), MemberStoredValueCard::getMemberPhone, memberStoredValueCard.getMemberPhone());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getStatus()), MemberStoredValueCard::getStatus, memberStoredValueCard.getStatus());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getStoreId()), MemberStoredValueCard::getStoreId, memberStoredValueCard.getStoreId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getCardManagementId()), MemberStoredValueCard::getCardManagementId, memberStoredValueCard.getCardManagementId());
        if (!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getBeginTime()) && !AbdulEmptyUtils.isEmpty(memberStoredValueCard.getEndTime())) {
            wrapper.between(MemberStoredValueCard::getCreateTime, memberStoredValueCard.getBeginTime(), memberStoredValueCard.getEndTime());
        }
        if (!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getExpireBeginTime()) && !AbdulEmptyUtils.isEmpty(memberStoredValueCard.getExpireEndTime())) {
            wrapper.between(MemberStoredValueCard::getExpiryEnd, memberStoredValueCard.getExpireBeginTime(), memberStoredValueCard.getExpireEndTime());
        }
        wrapper.eq(!AbdulEmptyUtils.isEmpty(memberStoredValueCard.getMemberId()), MemberStoredValueCard::getMemberId, memberStoredValueCard.getMemberId());
        wrapper.eq(MemberStoredValueCard::getStoreId, storeIdUtils.getStoreId());
        return this.page(new Page<>(memberStoredValueCard.getPageNum(), memberStoredValueCard.getPageSize()), wrapper);
    }

    /**
     * 购买定额卡
     *
     * @param memberStoredValueCard 请求对象
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(MemberStoredValueCard memberStoredValueCard) {
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getPayAmount())) {
            throw new RuntimeException("支付金额不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getGetIntegral())) {
            throw new RuntimeException("获得积分不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getBalance())) {
            throw new RuntimeException("充值金额不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getGiftBalance())) {
            throw new RuntimeException("赠送金额不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getPayType())) {
            throw new RuntimeException("支付方式不能为空");
        }
        //返回的购买的卡对象
        StoredValueCardManagement management = validateEntity(memberStoredValueCard, "购买的定额卡不存在");
        MemberList memberListServiceById = memberListService.getById(memberStoredValueCard.getMemberId());
        if (memberStoredValueCard.getGetIntegral() > 0) {
            memberListServiceById.setAvailablePoints(memberListServiceById.getAvailablePoints() + memberStoredValueCard.getGetIntegral());
            memberListServiceById.setTotalAvailablePoints(memberListServiceById.getTotalAvailablePoints() + memberStoredValueCard.getGetIntegral());
        }
        memberListServiceById.setAvailableBalance(memberListServiceById.getAvailableBalance().add(memberStoredValueCard.getBalance()));
        memberListServiceById.setAvailableGiftBalance(memberListServiceById.getAvailableGiftBalance().add(memberStoredValueCard.getGiftBalance()));
        memberListServiceById.setTotalBalance(memberListServiceById.getAvailableGiftBalance().add(memberListServiceById.getAvailableBalance()));
        memberListService.updateById(memberListServiceById);

        memberStoredValueCard.setCardNumber(BookingNumberGenerator.generateBookingNumber());
        memberStoredValueCard.setCardType(2);
        memberStoredValueCard.setStatus(1);
        memberStoredValueCard.setStoreName(storeIdUtils.getStore(storeIdUtils.getStoreId()).getStoreName());
        memberStoredValueCard.setStoreId(storeIdUtils.getStoreId());
        //todo 有效期的开始与结束 需要根据购买的储值卡定 目前暂定为十年
        memberStoredValueCard.setExpiryStart(LocalDate.now());
        memberStoredValueCard.setExpiryEnd(LocalDate.now().plusYears(10));
        memberStoredValueCard.setCardManagementId(management.getId());
        return this.save(memberStoredValueCard);
    }

    @Override
    public Boolean recharge(MemberStoredValueCard memberStoredValueCard) {
        StoredValueCardManagement management = validateEntity(memberStoredValueCard, "办理的充值卡不存在");
        memberStoredValueCard.setCardType(1);
        memberStoredValueCard.setCardNumber(BookingNumberGenerator.generateBookingNumber());
        memberStoredValueCard.setBalance(new BigDecimal(0));
        memberStoredValueCard.setGiftBalance(new BigDecimal(0));
        //todo 有效期的开始与结束 需要根据购买的储值卡定 目前暂定为十年
        memberStoredValueCard.setExpiryStart(LocalDate.now());
        memberStoredValueCard.setExpiryEnd(LocalDate.now().plusYears(10));
        memberStoredValueCard.setCardManagementId(management.getId());
        memberStoredValueCard.setStatus(1);
        memberStoredValueCard.setStoreName(storeIdUtils.getStore(storeIdUtils.getStoreId()).getStoreName());
        memberStoredValueCard.setStoreId(storeIdUtils.getStoreId());
        return this.save(memberStoredValueCard);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean rechargeCard(MemberStoredValueCardDTO cardDTO) {
        if (AbdulEmptyUtils.isEmpty(cardDTO.getCardNumber())) {
            throw new RuntimeException("请选择需要充值的会员储值卡");
        }
        LambdaQueryWrapper<MemberStoredValueCard> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(MemberStoredValueCard::getCardNumber, cardDTO.getCardNumber());
        MemberStoredValueCard storedValueCard = this.getOne(wrapper1);
        if (AbdulEmptyUtils.isEmpty(storedValueCard)) {
            throw new RuntimeException("会员储值卡不存在");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getPayAmount())) {
            throw new RuntimeException("请输入充值金额");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getPayType())) {
            throw new RuntimeException("请选择支付方式");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getBalance())) {
            throw new RuntimeException("请输入充值金额");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getGetIntegral())) {
            throw new RuntimeException("请输入获得积分");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getPayAmount())) {
            throw new RuntimeException("请输入支付金额");
        }
        //充值
        storedValueCard.setBalance(storedValueCard.getBalance().add(cardDTO.getBalance()));
        storedValueCard.setGiftBalance(storedValueCard.getGiftBalance().add(cardDTO.getGiftBalance()));
        storedValueCard.setPayAmount(cardDTO.getPayAmount());
        storedValueCard.setGetIntegral(cardDTO.getGetIntegral());
        storedValueCard.setPayType(cardDTO.getPayType());
        this.updateById(storedValueCard);
        //充值完成之后维护会员信息
        MemberList memberList = memberListService.getById(storedValueCard.getMemberId());
        if (AbdulEmptyUtils.isEmpty(memberList)) {
            throw new RuntimeException("会员不存在");
        }
        memberList.setAvailableBalance(memberList.getAvailableBalance().add(cardDTO.getBalance())); //可用余额
        memberList.setAvailableGiftBalance(memberList.getAvailableGiftBalance().add(cardDTO.getGiftBalance()));//可用赠送余额
        memberList.setTotalBalance(memberList.getAvailableBalance().add(memberList.getAvailableGiftBalance())); //总余额

        memberList.setAvailablePoints(memberList.getAvailablePoints() + cardDTO.getGetIntegral());//可用积分
        memberList.setTotalAvailablePoints(memberList.getTotalAvailablePoints() + cardDTO.getGetIntegral());//累计积分
        //添加充值记录
        MemberRechargeRecords rechargeRecords = new MemberRechargeRecords();
        LambdaQueryWrapper<MemberRechargeRecords> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberRechargeRecords::getMemberId, memberList.getId());
        wrapper.eq(MemberRechargeRecords::getCardNumber, storedValueCard.getCardNumber());
        wrapper.orderByDesc(MemberRechargeRecords::getCreateTime);
        wrapper.last("limit 1");
        MemberRechargeRecords rechargeRecordsLast = rechargeRecordsService.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(rechargeRecordsLast)) {
            rechargeRecords.setPreBalance(BigDecimal.ZERO);
            rechargeRecords.setPreGiftBalance(BigDecimal.ZERO);
        } else {
            rechargeRecords.setPreBalance(rechargeRecordsLast.getRechargeAmount());
            rechargeRecords.setPreGiftBalance(rechargeRecordsLast.getGiftAmount());
        }
        rechargeRecords.setRechargeId(BookingNumberGenerator.generateBookingNumber());
        rechargeRecords.setOrderType("充值卡充值");
        rechargeRecords.setMemberId(memberList.getId());
        rechargeRecords.setStatus(1);
        rechargeRecords.setRechargeStore(storeIdUtils.getStore(storeIdUtils.getStoreId()).getStoreName());
        rechargeRecords.setPaymentMethod(cardDTO.getPayType());
        rechargeRecords.setCardNumber(cardDTO.getCardNumber());
        rechargeRecords.setPoints(cardDTO.getGetIntegral());
        rechargeRecords.setCreateBy(cardDTO.getOperator());
        rechargeRecords.setCreateTime(new Date());
        rechargeRecords.setStoreId(storeIdUtils.getStoreId());
        rechargeRecords.setRemark(cardDTO.getRemark());
        rechargeRecordsService.save(rechargeRecords);
        //增加资金变动记录
        MemberChangeRecords changeRecords = moneyChangeRecords("充值", memberList.getId(), storedValueCard.getCardNumber(), cardDTO.getOperator(), cardDTO.getRemark());
//        LambdaQueryWrapper<MemberChangeRecords> lqw = Wrappers.lambdaQuery();
//        lqw.eq(MemberChangeRecords::getMemberId, memberList.getId());
//        lqw.eq(MemberChangeRecords::getCardNumber, storedValueCard.getCardNumber());
//        lqw.orderByDesc(MemberChangeRecords::getCreateTime);
//        lqw.last("limit 1");
//        MemberChangeRecords changeRecordsServiceOne = changeRecordsService.getOne(lqw);
//        if (AbdulEmptyUtils.isEmpty(changeRecordsServiceOne)) {
//            changeRecords.setPreBalance(BigDecimal.ZERO);
//            changeRecords.setPreGiftBalance(BigDecimal.ZERO);
//            changeRecords.setPostBalance(cardDTO.getBalance());
//            changeRecords.setPostGiftBalance(cardDTO.getGiftBalance());
//        } else {
//            changeRecords.setPreBalance(changeRecordsServiceOne.getPostBalance());
//            changeRecords.setPreGiftBalance(changeRecordsServiceOne.getPostGiftBalance());
//            changeRecords.setPostBalance(changeRecordsServiceOne.getPreBalance().add(cardDTO.getBalance()));
//            changeRecords.setPostGiftBalance(changeRecordsServiceOne.getPreGiftBalance().add(cardDTO.getGiftBalance()));
//        }
        moneyChangeRecords(changeRecords, memberList.getId(), storedValueCard.getCardNumber(), cardDTO);
        changeRecords.setChangeAmount(cardDTO.getBalance());
        changeRecords.setChangeGiftAmount(cardDTO.getGiftBalance());
        changeRecordsService.save(changeRecords);
        return memberListService.updateById(memberList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean give(MemberStoredValueCardDTO cardDTO) {
        MemberStoredValueCard memberStoredValueCard = validateMemberStoredValueCard(cardDTO);
        if (AbdulEmptyUtils.isEmpty(cardDTO.getGiftBalance()) || cardDTO.getGiftBalance().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("赠送金额必须不能为空");
        }
        memberStoredValueCard.setGiftBalance(memberStoredValueCard.getGiftBalance().add(cardDTO.getGiftBalance()));
        this.updateById(memberStoredValueCard);
        //维护会员信息
        MemberList memberListServiceById = memberListService.getById(memberStoredValueCard.getMemberId());
        if (AbdulEmptyUtils.isEmpty(memberListServiceById)) {
            throw new RuntimeException("会员不存在");
        }
        memberListServiceById.setAvailableGiftBalance(memberListServiceById.getAvailableGiftBalance().add(cardDTO.getGiftBalance()));
        memberListServiceById.setTotalBalance(memberListServiceById.getTotalBalance().add(cardDTO.getBalance()));
        //增加变动金额记录
        MemberChangeRecords changeRecords = moneyChangeRecords("赠送", memberStoredValueCard.getMemberId(), memberStoredValueCard.getCardNumber(), cardDTO.getOperator(), cardDTO.getRemark());
        cardDTO.setBalance(BigDecimal.ZERO);

        moneyChangeRecords(changeRecords, memberListServiceById.getId(), memberStoredValueCard.getCardNumber(), cardDTO);
        changeRecords.setChangeAmount(BigDecimal.ZERO);
        changeRecords.setChangeGiftAmount(cardDTO.getGiftBalance());
        changeRecordsService.save(changeRecords);
        return memberListService.updateById(memberListServiceById);
    }

    /**
     * 金额变动记录
     *
     * @param type       操作类型
     * @param memberId   会员id
     * @param cardNumber 卡号
     * @param operator   操作人
     * @param remark     备注
     */
    public MemberChangeRecords moneyChangeRecords(String type, Long memberId, String cardNumber, String operator, String remark) {
        MemberChangeRecords changeRecords = new MemberChangeRecords();
        changeRecords.setRecordId(BookingNumberGenerator.generateBookingNumber());
        changeRecords.setChangeType(type);
        changeRecords.setOperateStore(storeIdUtils.getStore(storeIdUtils.getStoreId()).getStoreName());
        changeRecords.setMemberId(memberId);
        changeRecords.setStoreId(storeIdUtils.getStoreId());
        changeRecords.setCardNumber(cardNumber);
        changeRecords.setCreateBy(operator);
        changeRecords.setCreateTime(new Date());
        changeRecords.setUpdateTime(new Date());
        changeRecords.setRemark(remark);
        return changeRecords;
    }

    /**
     * 金额变动记录可复用逻辑
     */
    public void moneyChangeRecords(MemberChangeRecords changeRecords, Long memberId, String cardNumber, MemberStoredValueCardDTO cardDTO) {
        LambdaQueryWrapper<MemberChangeRecords> lqw = Wrappers.lambdaQuery();
        lqw.eq(MemberChangeRecords::getMemberId, memberId);
        lqw.eq(MemberChangeRecords::getCardNumber, cardNumber);
        lqw.orderByDesc(MemberChangeRecords::getCreateTime);
        lqw.last("limit 1");
        MemberChangeRecords changeRecordsServiceOne = changeRecordsService.getOne(lqw);
        if (AbdulEmptyUtils.isEmpty(changeRecordsServiceOne)) {
            changeRecords.setPreBalance(BigDecimal.ZERO);
            changeRecords.setPreGiftBalance(BigDecimal.ZERO);
            changeRecords.setPostBalance(cardDTO.getBalance());
            changeRecords.setPostGiftBalance(cardDTO.getGiftBalance());
        } else {
            changeRecords.setPreBalance(changeRecordsServiceOne.getPostBalance());
            changeRecords.setPreGiftBalance(changeRecordsServiceOne.getPostGiftBalance());
            changeRecords.setPostBalance(changeRecordsServiceOne.getPreBalance().add(cardDTO.getBalance()));
            changeRecords.setPostGiftBalance(changeRecordsServiceOne.getPreGiftBalance().add(cardDTO.getGiftBalance()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean refund(MemberStoredValueCardDTO cardDTO) {
        if (AbdulEmptyUtils.isEmpty(cardDTO.getRefundAmount())) {
            throw new RuntimeException("请输入退款充值金额");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getRefundGiveAmount())) {
            throw new RuntimeException("请输入退款充值赠送金额");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getRefundPayType())) {
            throw new RuntimeException("请选择退款支付方式");
        }
        MemberStoredValueCard card = validateMemberStoredValueCard(cardDTO);
        if (card.getBalance().compareTo(cardDTO.getRefundAmount()) < 0) {
            throw new RuntimeException("退款金额不能大于储值卡余额");
        }
        if (card.getGiftBalance().compareTo(cardDTO.getRefundGiveAmount()) < 0) {
            throw new RuntimeException("退款赠送金额不能大于储值卡赠送余额");
        }
        card.setRefundAmount(cardDTO.getRefundAmount());
        card.setRefundGiveAmount(cardDTO.getRefundGiveAmount());
        card.setRefundPayType(cardDTO.getRefundPayType());
        if (!AbdulEmptyUtils.isEmpty(cardDTO.getRemark())) {
            card.setRemark(cardDTO.getRemark());
        }
        card.setBalance(card.getBalance().subtract(cardDTO.getRefundAmount()));
        card.setGiftBalance(card.getGiftBalance().subtract(cardDTO.getRefundGiveAmount()));
        card.setRefundTime(new Date());
        this.updateById(card);
        MemberList memberList = memberListService.getById(card.getMemberId());
        if (AbdulEmptyUtils.isEmpty(memberList)) {
            throw new RuntimeException("会员不存在");
        }
        memberList.setAvailableBalance(memberList.getAvailableBalance().subtract(cardDTO.getRefundAmount()));
        memberList.setAvailableGiftBalance(memberList.getAvailableGiftBalance().subtract(cardDTO.getRefundGiveAmount()));
        memberList.setTotalBalance(memberList.getTotalBalance().subtract(cardDTO.getRefundAmount()).subtract(cardDTO.getRefundGiveAmount()));
        return memberListService.updateById(memberList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean transfer(TransferDTO transferDTO) {
        if (AbdulEmptyUtils.isEmpty(transferDTO.getTransferOutMemberId()) || AbdulEmptyUtils.isEmpty(transferDTO.getReceiveMemberId()) || AbdulEmptyUtils.isEmpty(transferDTO.getCardNumber())) {
            return false;
        }
        //转卡操作
        //转出人 扣除会员信息里面的余额
        LambdaQueryWrapper<MemberStoredValueCard> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberStoredValueCard::getId, transferDTO.getCardNumber());
        wrapper.eq(MemberStoredValueCard::getMemberId, transferDTO.getTransferOutMemberId());
        MemberStoredValueCard valueCard = this.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(valueCard)) {
            throw new RuntimeException("转出的会员储值卡不存在");
        }
        MemberList outMember = memberListService.getById(transferDTO.getTransferOutMemberId());
        if (AbdulEmptyUtils.isEmpty(outMember)) {
            throw new RuntimeException("此会员无效或会员不存在");
        }
        outMember.setAvailableBalance(outMember.getAvailableBalance().subtract(valueCard.getBalance()));//可用余额
        outMember.setAvailableGiftBalance(outMember.getAvailableGiftBalance().subtract(valueCard.getGiftBalance()));//可用赠送余额
        outMember.setTotalBalance(outMember.getTotalBalance().subtract(valueCard.getBalance()).subtract(valueCard.getGiftBalance()));//总余额
        memberListService.updateById(outMember);
        //接收人
        MemberList receivePeople = memberListService.getById(transferDTO.getReceiveMemberId());
        if (AbdulEmptyUtils.isEmpty(receivePeople)) {
            throw new RuntimeException("接收人会员不存在");
        }
        receivePeople.setTotalBalance(receivePeople.getTotalBalance().add(valueCard.getBalance()).add(valueCard.getGiftBalance()));
        receivePeople.setAvailableBalance(receivePeople.getAvailableBalance().add(valueCard.getBalance()));
        receivePeople.setAvailableGiftBalance(receivePeople.getAvailableGiftBalance().add(valueCard.getGiftBalance()));
        memberListService.updateById(receivePeople);

        valueCard.setMemberId(receivePeople.getId());
        valueCard.setMemberPhone(receivePeople.getPhone());
        return this.updateById(valueCard);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean transferAccounts(TransferAccountsDTO transferAccountsDTO) {
        if (AbdulEmptyUtils.isEmpty(transferAccountsDTO.getCardNumber()) || AbdulEmptyUtils.isEmpty(transferAccountsDTO.getReceiveCardNumber()) || AbdulEmptyUtils.isEmpty(transferAccountsDTO.getTransferOutMemberId())
                || AbdulEmptyUtils.isEmpty(transferAccountsDTO.getReceiveMemberId()) || AbdulEmptyUtils.isEmpty(transferAccountsDTO.getTransferAmount())) {
            return false;
        }
        //转出
        LambdaQueryWrapper<MemberStoredValueCard> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberStoredValueCard::getMemberId, transferAccountsDTO.getTransferOutMemberId());
        wrapper.eq(MemberStoredValueCard::getCardNumber, transferAccountsDTO.getCardNumber());
        MemberStoredValueCard valueCard = this.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(valueCard)) {
            throw new RuntimeException("会员储值卡不存在");
        }
        if (valueCard.getBalance().subtract(transferAccountsDTO.getTransferAmount()).compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("转账金额不能大于储值卡余额");
        }
        if (valueCard.getGiftBalance().subtract(transferAccountsDTO.getGiveAmount()).compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("转账赠送金额不能大于储值卡赠送余额");
        }
        valueCard.setBalance(valueCard.getBalance().subtract(transferAccountsDTO.getTransferAmount()));
        valueCard.setGiftBalance(valueCard.getGiftBalance().subtract(transferAccountsDTO.getGiveAmount()));
        this.updateById(valueCard);
        // 更新转出会员信息
        MemberList outPeople = memberListService.getById(transferAccountsDTO.getTransferOutMemberId());
        if (AbdulEmptyUtils.isEmpty(outPeople)) {
            throw new RuntimeException("转出会员不存在");
        }
        outPeople.setAvailableBalance(outPeople.getAvailableBalance().subtract(transferAccountsDTO.getTransferAmount())); //可用余额
        outPeople.setAvailableGiftBalance(outPeople.getAvailableGiftBalance().subtract(transferAccountsDTO.getGiveAmount())); //可用赠送余额
        outPeople.setTotalBalance(outPeople.getTotalBalance().subtract(transferAccountsDTO.getTransferAmount().subtract(transferAccountsDTO.getGiveAmount())));
        memberListService.updateById(outPeople);
        //更新接收会员储值卡信息
        LambdaQueryWrapper<MemberStoredValueCard> receiveWrapper = Wrappers.lambdaQuery();
        receiveWrapper.eq(MemberStoredValueCard::getMemberId, transferAccountsDTO.getReceiveMemberId());
        receiveWrapper.eq(MemberStoredValueCard::getCardNumber, transferAccountsDTO.getReceiveCardNumber());
        MemberStoredValueCard receiveCard = this.getOne(receiveWrapper);
        if (AbdulEmptyUtils.isEmpty(receiveCard)) {
            throw new RuntimeException("接收者会员储值卡不存在");
        }
        receiveCard.setBalance(receiveCard.getBalance().add(transferAccountsDTO.getTransferAmount()));
        receiveCard.setGiftBalance(receiveCard.getGiftBalance().add(transferAccountsDTO.getGiveAmount()));
        this.updateById(receiveCard);
        //更新接收会员信息
        MemberList receivePeople = memberListService.getById(transferAccountsDTO.getReceiveMemberId());
        if (AbdulEmptyUtils.isEmpty(receivePeople)) {
            throw new RuntimeException("接收者会员不存在");
        }
        receivePeople.setAvailableBalance(receivePeople.getAvailableBalance().add(transferAccountsDTO.getTransferAmount()));
        receivePeople.setAvailableGiftBalance(receivePeople.getAvailableGiftBalance().add(transferAccountsDTO.getGiveAmount()));
        receivePeople.setTotalBalance(receivePeople.getTotalBalance().add(transferAccountsDTO.getTransferAmount().add(transferAccountsDTO.getGiveAmount())));
        return memberListService.updateById(receivePeople);
    }

    @Override
    public boolean integralExchange(MemberStoredValueCardDTO cardDTO) {

        return false;
    }

    /**
     * 判断会员储值卡是否存在
     */
    public MemberStoredValueCard validateMemberStoredValueCard(MemberStoredValueCardDTO cardDTO) {
        if (AbdulEmptyUtils.isEmpty(cardDTO.getCardNumber())) {
            throw new RuntimeException("会员储值卡号不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(cardDTO.getMemberId())) {
            throw new RuntimeException("会员ID不能为空");
        }
        LambdaQueryWrapper<MemberStoredValueCard> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberStoredValueCard::getMemberId, cardDTO.getMemberId());
        wrapper.eq(MemberStoredValueCard::getCardNumber, cardDTO.getCardNumber());
        MemberStoredValueCard memberStoredValueCard = this.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard)) {
            throw new RuntimeException("会员储值卡不存在");
        }
        return memberStoredValueCard;
    }

    /**
     * 非空判断
     */
    private StoredValueCardManagement validateEntity(MemberStoredValueCard memberStoredValueCard, String message) {
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getMemberId())) {
            throw new RuntimeException("会员ID不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getMemberPhone())) {
            throw new RuntimeException("会员手机号不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getCardName())) {
            throw new RuntimeException("会员卡名称不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberStoredValueCard.getCardManagementId())) {
            throw new RuntimeException("定额卡编号不能为空");
        }
        //判断会员是否存在
        MemberList memberListServiceById = memberListService.getById(memberStoredValueCard.getMemberId());
        if (AbdulEmptyUtils.isEmpty(memberListServiceById)) {
            throw new RuntimeException("会员不存在");
        }
        LambdaQueryWrapper<StoredValueCardManagement> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StoredValueCardManagement::getId, memberStoredValueCard.getCardManagementId());
        wrapper.eq(StoredValueCardManagement::getCardName, memberStoredValueCard.getCardName());
        StoredValueCardManagement management = storedValueCardManagementService.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(management)) {
            throw new RuntimeException(message);
        }
        return management;
    }
}
